<template>
	<view>
		<cu-custom bgColor="bg-gradual-green" :isBack="true">
			<view slot="backText">返回</view>
			<view slot="content">活动修改</view>
		</cu-custom>
		<view class="cu-bar bg-white">
			<view class="action">
				<text class="cuIcon-titles text-green"></text>
				<text class="text-bold">活动修改</text>
			</view>
		</view>
		<form>
			<view class="cu-form-group">
				<view class="title">
					<text style="color:red">*</text>
					活动名称:
				</view>
				<input v-model.lazy="activityInfo.title" :placeholder="activityInfo.title"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">
					<text style="color:red">*</text>
					活动人数:
				</view>
				<input v-model.lazy="activityInfo.numOfPerson" :placeholder="activityInfo.numOfPerson"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">
					<text style="color:red">*</text>
					活动类别:
				</view>
				<input v-model.lazy="activityInfo.category" :placeholder="activityInfo.category"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">
					<text style="color:red">*</text>
					活动时间:
				</view>
				<picker mode="date" :value="activityInfo.time" @change="dateChange">
					<view class="text-green">{{activityInfo.time}}</view>
				</picker>
			</view>
			<view class="cu-form-group justify-start">
				<view class="title">
					<text style="color:red">*</text>
					活动地点:
				</view>
				<view @click="choosePlace" class="text-green">{{activityInfo.place.name}}</view>
			</view>
			<view class="cu-form-group align-start">
				<view class="title">
					<text style="color:red">*</text>
					活动介绍:
				</view>
				<textarea maxlength="-1" v-model.lazy="activityInfo.content" :placeholder="activityInfo.content"></textarea>
			</view>
			<view class="cu-bar bg-white margin-top-xs">
				<view class="action">图片上传</view>
				<view class="action">{{imgList.length}}/9</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" v-for="(img,index) in imgList" :key="index"
						@click="viewImage($event, imgList[index])">
						<image :src='imgList[index]' mode='aspectFill'></image>
						<view class="cu-tag bg-red" @click.stop="deleteImage($event, index)">
							<text class="cuIcon-close"></text>
						</view>
					</view>
					<view class="solids" @click="chooseImage" v-if="imgList.length<9">
						<text class="cuIcon-cameraadd"></text>
					</view>
				</view>
			</view>
		</form>
		<view class="flex padding justify-center"
			style="padding-bottom: calc(140upx + env(safe-area-inset-bottom) / 2);">
			<button class="cu-btn lg bg-green" @click="submitForm">点击提交</button>
		</view>
	</view>
</template>

<script>
	const util = require('../../utils/util.js');
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				url: this.url,
				activityInfo: {
					title: '',
					category: '',
					numOfPerson: '',
					time: '点击选择活动时间',
					content: '',
					place: {
						name: '点击在地图中选择活动地点',
						address: '',
						latitude: 0,
						longitude: 0
					}
				},
				imgList: [],
			}
		},
		computed: {
			...mapState(['userInfo']),
			imgNameList() {
				let img = []
				this.imgList.forEach(imgUrl => {
					img.push(imgUrl.slice(11))
				})
				return img
			}
		},
		methods: {
			dateChange(e){
				this.activityInfo.time = e.detail.value
			},
			choosePlace() {
				uni.chooseLocation({
					success: (res) => {
						this.activityInfo.place.latitude = res.latitude
						this.activityInfo.place.longitude = res.longitude
						this.activityInfo.place.name = res.name
						this.activityInfo.place.address = res.address
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			chooseImage() {
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择或从拍照选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						this.isImage = true
					}
				})
			},
			viewImage(e, url) {
				uni.previewImage({
					urls: this.imgList,
					current: url
				})
			},
			deleteImage(e, index) {
				this.imgList.splice(index, 1)
				if (this.imgList.length == 0) {
					this.isImage = false
				}
			},
			submitImage() {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '图片上传中...'
					})
					var time = util.formatTimestring(new Date());
					let promiseArr = [];
					for (let i = 0; i < this.imgList.length; i++) {
						let promise = new Promise((resolve, reject) => {
							var randstring = Math.floor(Math.random() * 1000000).toString() +
								'.png'
							randstring = time + '-' + randstring
							uni.uploadFile({
								url: this.url + '/image',
								filePath: this.imgList[i],
								name: 'uploadFile',
								header: {
									'content-type': 'multipart/form-data'
								},
								success: (res) => {
									console.log(res)
									if(res.statusCode == 200){
										resolve(res)
									}else {
										reject(res)
									}
								},
								fail: (err) => {
									reject(err)
								}
							})
						})
						promiseArr.push(promise)
					}
					Promise.all(promiseArr).then((result) => {
						uni.hideLoading()
						resolve()
					}).catch(err => {
						console.log('err', err)
						reject()
					})
				})
			},
			async submitForm() {
				if (this.userInfo.userName == '') {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else {
					if (this.activityInfo.title.trim().length == 0 || this.activityInfo.content.trim().length == 0)
						return uni.showToast({
							title: '问题标题或内容不能为空!',
							icon: 'none'
						})
					uni.request({
						method: 'PUT',
						url: this.url + '/activity',
						header: {
							Authorization: 'Bearer ' + this.userInfo.token
						},
						data: {
							// activity: {
							...this.activityInfo,
							imgList: this.imgNameList,
							publisher: this.userInfo.userName,
							// }
						},
						success: (res) => {
							console.log(res)
							if (res.statusCode == 200) {
								this.submitImage().then(() => {
									uni.showToast({
										title: '活动修改成功',
										icon: 'none'
									})
									uni.navigateBack()
								})
							} else {
								uni.showToast({
									title: '请求失败!',
								})
							}
						}
					})
				}
			}
		},
		onLoad(option) {
			uni.request({
				method: 'GET',
				url: this.url + '/home/create/' + option.id,
				header: {
					Authorization: 'Bearer ' + this.userInfo.token
				},
				success: (res) => {
					console.log(res)
					if(res.statusCode == 200){
						this.activityInfo = res.data
						this.imgList = res.data.imgList
						delete this.activityInfo.imgList
					}
				}
			})
		}
	}
</script>

<style>

</style>
